package com.atguigu.ggkt.sequence.service.impl;

import com.atguigu.ggkt.result.Result;
import com.atguigu.ggkt.sequence.Constants;
import com.atguigu.ggkt.sequence.service.SequenceService;
import com.atguigu.ggkt.utils.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author Tony Xi
 * @since 20240817
 */
@Component
public class SequenceImpl_1 implements SequenceService {

    @Resource
    RedisTemplate redisTemplate;

    @Override
    public String create() {
        // 时间部分 17 位
        String now = DateUtil.localDateNowString();
        now = StringUtils.rightPad(now, 17, "0");
        // 数字部分 9 位
        Long increment = redisTemplate.opsForValue().increment(Constants.PUBLIC);
        if (increment == null || increment >= 999999999) {
            redisTemplate.opsForValue().set(Constants.PUBLIC, 0);
            increment = redisTemplate.opsForValue().increment(Constants.PUBLIC);
        }

        StringBuilder builder = new StringBuilder();
        String num = StringUtils.leftPad(String.valueOf(increment), 9, "0");

        // combine 27 位
        builder.append(now).append("P").append(num);

        return builder.toString();
    }
}
